package com.sh.xxj.rebot.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.hn.net.Kit;
import com.sh.xxj.rebot.model.CourseModel;
import com.sh.xxj.rebot.model.CourseOptionModel;
import com.sh.xxj.rebot.model.TypeModel;

/**
 * 课程服务
 * 
 * @author sh
 * 
 */
public class CourseService {

	public static void main(String[] args) throws DocumentException,
			IOException {
		CourseService cs = new CourseService();

		// String data=null;
		//
		// data=Tools.readFile("res\\data\\parent\\menu.xml");

		List<TypeModel> listTypeModel = cs
				.getTypeModeFromFilePath("res\\data\\parent\\menu.xml");
		System.out.println(listTypeModel);
		cs.writeTypeModelToFile(listTypeModel, "res\\data\\chinese\\menu.xml");
	}

	/**
	 * 下载所有声音
	 * 
	 * @param listTypeModel
	 * @return
	 */
	public void downloadVoices(List<TypeModel> listTypeModel) {
		String courseFilePath;
		// 循环类型
		for (TypeModel typeModel : listTypeModel) {
			// 循环课件
			for (CourseModel courseModel : typeModel.getListCourseModel()) {
				// 路径
				courseFilePath = ConfigService.OUTPUT_PATH ;
//						+ File.separator
//						+ courseModel.getCourse();
				// 循环课件按钮
				for (CourseOptionModel courseOptionModel : courseModel
						.getListCourseOptionModel()) {
					// 下载声音
					downloadVoice(courseOptionModel.getWord(), courseFilePath,
							courseOptionModel.getStudyAudio());
				}// end for(循环课件按钮)
			}// end for(循环课件)
		}// end for(循环类型)
	}

	/**
	 * 下载声音
	 * 
	 * @param word
	 * @param filePath
	 * @param filename
	 */
	public void downloadVoice(String word, String filePath, String filename) {
		try {
			byte[] arrVoice = VoiceService.getVoiceBytes(word);
			VoiceService.writeToFile(arrVoice, filePath, filename);
			System.out.println("下载_"+word+"成功!");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("再试一次.");
			downloadVoice(word, filePath, filename);
		}
	}

	/**
	 * 翻译文字
	 * 
	 * @param listTypeModel
	 *            数据列表
	 * @return
	 */
	public List<TypeModel> translateTextLanuage(List<TypeModel> listTypeModel) {
		// 类型名字
		String tName;
		// 课件名字
		String cName;
		// 课件按钮名字
		String coName;
		// 循环类型
		for (TypeModel typeModel : listTypeModel) {
			tName = typeModel.getName();
			tName = getTranslate(tName);
			typeModel.setName(tName);
			// 循环课件
			for (CourseModel courseModel : typeModel.getListCourseModel()) {
				cName = courseModel.getName();
				cName = getTranslate(cName);
				courseModel.setName(cName);
				// 循环课件按钮
				for (CourseOptionModel courseOptionModel : courseModel
						.getListCourseOptionModel()) {
					coName = courseOptionModel.getWord();
					System.out.println("翻译_"+coName);
					coName = getTranslate(coName);
					System.out.println("翻译完成_"+coName);
					courseOptionModel.setWord(coName);
				}// end for(循环课件按钮)
			}// end for(循环课件)
		}// end for(循环类型)
		return listTypeModel;
	}

	/**
	 * 得到翻译字体
	 * 
	 * @param word
	 * @return
	 */
	public String getTranslate(String word) {
		String strBack = null;
		String url = ConfigService.TRANSLATE_API;
		String tWord = null;
		try {
			tWord = java.net.URLEncoder.encode(word, "UTF-8");
			String requestURL = url.replaceAll("@p1@", tWord);
			strBack = Kit.httpRequest(requestURL, null, "GET", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (strBack == null) {
			strBack = getTranslate(word);
		} else {
			int iStartIndex = strBack.indexOf("\"");
			int iEndIndex = strBack.indexOf("\"", iStartIndex + 1);
			strBack = strBack.substring(iStartIndex + 1, iEndIndex);
		}
		return strBack;
	}

	/**
	 * 写课程到文件
	 * 
	 * @param listTypeModel
	 * @param outputFile
	 * @throws IOException
	 */
	public void writeTypeModelToFile(List<TypeModel> listTypeModel,
			String outputFile) throws IOException {
		Document document = DocumentHelper.createDocument();

		Element root = document.addElement("Root");

		// 分类
		for (TypeModel typeModel : listTypeModel) {
			Element eleTypeModel = root
					.addElement("menu")
					.addAttribute("name", typeModel.getName())
					.addAttribute("id", typeModel.getId())
					.addAttribute("sort", typeModel.getSort())
					.addAttribute("studyAudio", typeModel.getStudyAudio())
					.addAttribute("backgroundMusic",
							typeModel.getBackgroundMusic())
					.addAttribute("backgroundPic", typeModel.getBackgroundPic());
			// 课程
			for (CourseModel courseModel : typeModel.getListCourseModel()) {
				Element eleCourseModel = eleTypeModel.addElement("submenu")
						.addAttribute("id", courseModel.getId())
						.addAttribute("name", courseModel.getName())
						.addAttribute("course", courseModel.getCourse())
						.addAttribute("sort", courseModel.getSort());
				// 课程的按钮
				for (CourseOptionModel courseOptionModel : courseModel
						.getListCourseOptionModel()) {
					Element eleCourseOptionModel = eleCourseModel
							.addElement("option")
							.addAttribute("id", courseOptionModel.getId())
							.addAttribute("pic", courseOptionModel.getPic())
							.addAttribute("studyAudio",
									courseOptionModel.getStudyAudio())
							.addAttribute("questionAudio",
									courseOptionModel.getQuestionAudio())
							.addAttribute("sort", courseOptionModel.getSort())
							.addAttribute("word", courseOptionModel.getWord());
				}// end for(课程的按钮)
			}// end for(课程)

		}// end for(分类)

		// Element element1 = root.addElement("user")
		// .addAttribute("name", "Alexander")
		// .addAttribute("blog", "http://netnova.blogjava.net")
		// .addText("我是中文的名字");

		XMLWriter writer = new XMLWriter(new FileOutputStream(outputFile));

		writer.write(document);
		writer.close();
	}

	/**
	 * 从字符串得到课程数据
	 * 
	 * @param data
	 * @return
	 * @throws DocumentException
	 */
	public List<TypeModel> getTypeModeFromFilePath(String dataPath)
			throws DocumentException {

		SAXReader reader = new SAXReader();
		File file = new File(dataPath);
		Document document = reader.read(file);
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
		// 类型类别
		List<TypeModel> listTypeModel = new ArrayList<TypeModel>();
		for (Element eleTypeModel : childElements) {
			TypeModel typeModel = new TypeModel();
			// 未知属性名情况下
			/*
			 * List<Attribute> attributeList = child.attributes(); for
			 * (Attribute attr : attributeList) {
			 * System.out.println(attr.getName() + ": " + attr.getValue()); }
			 */

			// 填充属性
			typeModel.setId(eleTypeModel.attributeValue("id"));
			typeModel.setBackgroundMusic(eleTypeModel
					.attributeValue("backgroundMusic"));
			typeModel.setBackgroundPic(eleTypeModel
					.attributeValue("backgroundPic"));
			typeModel.setName(eleTypeModel.attributeValue("name"));
			typeModel.setSort(eleTypeModel.attributeValue("sort"));
			typeModel.setStudyAudio(eleTypeModel.attributeValue("studyAudio"));

			// 课件模型
			List<Element> elementList = eleTypeModel.elements();

			List<CourseModel> listCourseModel = new ArrayList<CourseModel>();
			for (Element eleCourseModel : elementList) {
				// 创建课件并填充属性
				CourseModel courseModel = new CourseModel();
				courseModel.setId(eleCourseModel.attributeValue("id"));
				courseModel.setCourse(eleCourseModel.attributeValue("course"));
				courseModel.setSort(eleCourseModel.attributeValue("sort"));
				courseModel.setName(eleCourseModel.attributeValue("name"));
				// 课件所属的类型填充
				courseModel.setTypeModel(typeModel);

				// 课件按钮模型
				List<Element> courseModelList = eleCourseModel.elements();
				List<CourseOptionModel> listCourseOptionModel = new ArrayList<CourseOptionModel>();
				for (Element eleCourseOptionModel : courseModelList) {
					// 创建按钮模型并填充
					CourseOptionModel courseOptionModel = new CourseOptionModel();
					courseOptionModel.setId(eleCourseOptionModel
							.attributeValue("id"));
					courseOptionModel.setQuestionAudio(eleCourseOptionModel
							.attributeValue("questionAudio"));
					courseOptionModel.setWord(eleCourseOptionModel
							.attributeValue("word"));
					courseOptionModel.setSort(eleCourseOptionModel
							.attributeValue("sort"));
					courseOptionModel.setStudyAudio(eleCourseOptionModel
							.attributeValue("studyAudio"));
					courseOptionModel.setPic(eleCourseOptionModel
							.attributeValue("pic"));
					courseOptionModel.setCourseModel(courseModel);
					// 填充到数组中
					listCourseOptionModel.add(courseOptionModel);
				}// end for(课件按钮模型)
					// 课程模型填充按钮
				courseModel.setListCourseOptionModel(listCourseOptionModel);
				listCourseModel.add(courseModel);
			}// end for(课件模型)
				// System.out.println();
			//
			// //已知子元素名的情况下
			// System.out.println("title" + typeModel.elementText("course"));
			// System.out.println("author" + typeModel.elementText("sort"));
			// //这行是为了格式化美观而存在
			// System.out.println();
			typeModel.setListCourseModel(listCourseModel);
			listTypeModel.add(typeModel);
		}

		return listTypeModel;
	}
}
